package com.demo.interpector;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.demo.annotation.LoginFilter;
import com.demo.annotation.MobileMethod;
import com.demo.mobile.DES;
import com.demo.mobile.MFrameEnumError;
import com.demo.util.PattenUtil;
import com.demo.util.ProtobufUtils;
import com.demo.validator.LoginInterface;
import com.demo.validator.ValidateFactory;
import com.google.gson.Gson;
import com.mdx.mobile.base.Retn;
/**
 * 为mvc做登录过滤
 * @author Administrator
 *
 */
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest req,
			HttpServletResponse resp, Object handler, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * 为添加loginFilter的方法和controller验证是否登录
	 */
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse resp,
			Object handler) throws Exception {
		try {
			if(!(handler instanceof HandlerMethod)){
				return true;
			}
			HandlerMethod method = (HandlerMethod)handler;
			
			//验证controller 是否带有注解loginFilter
			LoginFilter filter = method.getBean().getClass().getAnnotation(LoginFilter.class);
			
			if(filter!=null){//验证是否已登录
				LoginInterface loginValidate = ValidateFactory.newInstance(filter.validateClz());
				if(loginValidate.isLogin(req)){//已登录
					return true;
				}
				//是否为mobile方法
				MobileMethod mobileMethod =  method.getBean().getClass().getAnnotation(MobileMethod.class);
				if(mobileMethod==null){
					// 如果是ajax请求响应头会有，x-requested-with
					if (req.getHeader("x-requested-with") != null
							&& req.getHeader("x-requested-with").equalsIgnoreCase(
									"XMLHttpRequest")) {
						// 在响应头设置session状态
						resp.setHeader("sessionstatus", "sessionOut");
						resp.getWriter().print("sessionOut");
					} else {
						String outPage =PattenUtil.formatOutPage( filter.outpage(), req);
						resp.sendRedirect(outPage);
					}
				}else{
					//处理手机端未登录
					Retn.Msg_Retn.Builder returnBuilder = Retn.Msg_Retn.newBuilder();
					returnBuilder.setErrorCode(MFrameEnumError.LOGIN_FAIL_ERROR.getErrorCode());
					returnBuilder.setErrorMsg(MFrameEnumError.LOGIN_FAIL_ERROR.getErrorMsg());
					boolean debug = "1".equals(req.getParameter("debug"));
					try {
						if (!debug) {
							 resp.getOutputStream().write(new DES().desEncrypt(ProtobufUtils.serialize(returnBuilder)));
//							com.mdx.mobile.commons.data.Method.protobufSeralizeDes(returnBuilder, sos);
						} else {
							resp.setContentType("text/plain; charset=utf-8");
							resp.setCharacterEncoding("UTF-8");
							Map<String, Object> jsonShow = new HashMap<String, Object>();
							jsonShow.put("errorCode", Integer.valueOf(returnBuilder.getErrorCode()));
							jsonShow.put("errorMsg", returnBuilder.getErrorMsg());

							resp.getOutputStream().write(new Gson().toJson(jsonShow).getBytes("UTF-8"));
						}
						resp.getOutputStream().flush();
					} catch (Exception e) {
					} finally {
						if (resp.getOutputStream() != null){
							resp.getOutputStream().close();
						}
					}
				}
				
				return false;
			}
			//filter 不存在 验证method 是否存在loginFilter
			filter= method.getMethodAnnotation(LoginFilter.class);
			
			if(filter==null){// controller 和 method 均 未加loginFilter注解 无需验证登录
				return true;
			}
			//method 上存在注解 验证登录
			LoginInterface loginValidate = ValidateFactory.newInstance(filter.validateClz());
			if(loginValidate.isLogin(req)){//已登录
				return true;
			}
			//是否为mobile方法
			MobileMethod mobileMethod =  method.getMethodAnnotation(MobileMethod.class);
			if(mobileMethod==null){
				// 如果是ajax请求响应头会有，x-requested-with
				if (req.getHeader("x-requested-with") != null
						&& req.getHeader("x-requested-with").equalsIgnoreCase(
								"XMLHttpRequest")) {
					// 在响应头设置session状态
					resp.setHeader("sessionstatus", "sessionOut");
					resp.getWriter().print("sessionOut");
				} else {
					String outPage =PattenUtil.formatOutPage( filter.outpage(), req);
					resp.sendRedirect(outPage);
				}
			}else{
				//处理手机端未登录
				Retn.Msg_Retn.Builder returnBuilder = Retn.Msg_Retn.newBuilder();
				returnBuilder.setErrorCode(MFrameEnumError.LOGIN_FAIL_ERROR.getErrorCode());
				returnBuilder.setErrorMsg(MFrameEnumError.LOGIN_FAIL_ERROR.getErrorMsg());
				boolean debug = "1".equals(req.getParameter("debug"));
				try {
					if (!debug) {
						 resp.getOutputStream().write(new DES().desEncrypt(ProtobufUtils.serialize(returnBuilder)));
//						com.mdx.mobile.commons.data.Method.protobufSeralizeDes(returnBuilder, sos);
					} else {
						resp.setContentType("text/plain; charset=utf-8");
						resp.setCharacterEncoding("UTF-8");
						Map<String, Object> jsonShow = new HashMap<String, Object>();
						jsonShow.put("errorCode", Integer.valueOf(returnBuilder.getErrorCode()));
						jsonShow.put("errorMsg", returnBuilder.getErrorMsg());

						resp.getOutputStream().write(new Gson().toJson(jsonShow).getBytes("UTF-8"));
					}
					resp.getOutputStream().flush();
				} catch (Exception e) {
				} finally {
					if (resp.getOutputStream() != null){
						resp.getOutputStream().close();
					}
				}
			}
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
}
